<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id?"编辑企业":"添加企业" }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addFormRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryList" :key="item.industryCode" :value="item.industryCode" :label="item.industryName" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                class="upload-demo"
                action="#"
                :http-request="uploadRequest"
                :before-upload="beforeUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg，文件大小不得超过5M</div>

                <div v-if="addForm.businessLicenseUrl" class="preview-container">
                  <img :src="addForm.businessLicenseUrl" class="preview-image">
                  <span class="preview-name">{{ fileName }}</span>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getIndustryListAPI, createExterpriseAPI, getExterpriseDetailAPI, editExterpriseAPI } from '@/api/enterprise'
import { uploadAPI } from '@/api/common'
export default {
  data() {
    const validatePhone = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正常的手机号'))
      }
    }
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      addFormRules: { name: [{ required: true, message: '企业名称为必填', trigger: 'blur' }],
        legalPerson: [{ required: true, message: '法人名称为必填', trigger: 'blur' }],
        registeredAddress: [{ required: true, message: '注册地址为必填', trigger: 'blur' }],
        industryCode: [{ required: true, message: '所在行业为必填', trigger: 'blur' }],
        contact: [{ required: true, message: '企业联系人为必填', trigger: 'blur' }],
        contactNumber: [{ required: true, message: '联系人电话为必填', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        businessLicenseId: [{ required: true, message: '请上传营业执照', trigger: 'blur' }]
      },
      fileList: [], // 新增
      fileName: '', // 新增
      industryList: []
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }

  },
  mounted() {
    if (this.id) {
      this.getExterpriseDetail()
    }
    this.getIndustryList()
  },
  methods: {
    // 获取公司详情
    async getExterpriseDetail() {
      const { data } = await getExterpriseDetailAPI(this.id)
      // console.log(data)
      // this.addForm = data
      const { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress, id } = data
      this.addForm = { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress, id }
    },
    // 查询企业所属行业列表
    async getIndustryList() {
      const res = await getIndustryListAPI()
      // console.log(res)
      this.industryList = res.data
    },
    // 上传图片文件请求
    async uploadRequest({ file }) {
      // const file = data.file
      try {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', 'businessLicense')

        const res = await uploadAPI(formData)
        console.log('上传成功:', res)

        // 赋值表单数据
        this.addForm.businessLicenseId = res.data.id
        this.addForm.businessLicenseUrl = res.data.url

        // 更新文件列表和文件名
        this.fileList = [{
          name: file.name,
          url: res.url
        }]
        this.fileName = file.name

        // 清除错误信息
        this.$refs.ruleForm.validateField('businessLicenseId')

        this.$message.success('上传成功')
      } catch (error) {
        console.error('上传失败:', error)
        this.$message.error('上传失败，请重试')
      }
    },
    // 删除上传文件后所作的操作
    handleRemove() {
      this.fileList = []
      this.addForm.businessLicenseId = ''
      this.addForm.businessLicenseUrl = ''
      this.fileName = ''
      this.$refs.ruleForm.validateField('businessLicenseId')
      this.$message.info('已删除上传的文件')
    },
    // 检验上传文件
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 表单提交
    confirmSubmit() {
      this.$refs.ruleForm.validate(async(flag) => {
        // console.log(flag)
        if (!flag) return
        // 添加调试信息，确认表单数据完整
        // console.log('提交前的完整表单数据:')
        // console.log('企业名称(name):', this.addForm.name)
        // console.log('法人(legalPerson):', this.addForm.legalPerson)
        // console.log('营业执照ID(businessLicenseId):', this.addForm.businessLicenseId)
        // console.log('营业执照URL(businessLicenseUrl):', this.addForm.businessLicenseUrl)
        // console.log('完整对象:', JSON.stringify(this.addForm, null, 2))
        if (this.id) {
          await editExterpriseAPI(this.addForm)
          this.$message.success('编辑成功')
        } else {
          await createExterpriseAPI(this.addForm)
          this.$message.success('新增成功')
        }

        // this.$router.back()
        this.$router.go(-1)
      })
    },
    handlePreview(file) {
      console.log(file)
    }
  }
}
</script>

<style scoped lang="scss">
/* 添加预览样式 */
.preview-container {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.preview-image {
  width: 100px;
  height: 100px;
  object-fit: contain;
  border: 1px solid #eee;
  margin-right: 10px;
}

.preview-name {
  font-size: 14px;
  color: #666;
}
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
